package com.diko.ucenter.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.diko.commonUtils.BizCodeEnume;
import com.diko.commonUtils.R;
import com.diko.ucenter.constant.AuthServerConstant;
import com.diko.ucenter.entity.Member2;
import com.diko.ucenter.entity.vo.SocialUserVo;
import com.diko.ucenter.service.Member2Service;
import com.diko.ucenter.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Emma Li
 * @date 2021/3/27 - 21:25
 */
@Controller
@Slf4j
@CrossOrigin
@RequestMapping("api/ucenter/weibo")
public class WeiboApiController {
    @Autowired
    Member2Service member2Service;

    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session, HttpServletResponse servletResponse) throws Exception {

        // 根据code换取accessToken
        Map<String, String> map = new HashMap<>();
//        map.put("client_id", "908582850");
        map.put("client_id", "461539103");
//        map.put("client_secret", "6226758e6e6d623d1bceccefccf22a0d");
        map.put("client_secret", "211fe18eb6f37066b0c43b384c241896");
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://emma.free.idcfengye.com/api/ucenter/weibo/oauth2.0/weibo/success");
        map.put("code", code);
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<String, String>(), null, map);

        // 2、处理响应数据
        if (response.getStatusLine().getStatusCode() == 200) {
            // 获取到了accessTokens
            String json = EntityUtils.toString(response.getEntity()); // 将响应的内容转换成json字符串
            SocialUserVo socialUserVo = JSON.parseObject(json, SocialUserVo.class); // 将获取到的json转换成SocialUserVo对象

            // 1、会员第一次登陆，自动注册（为当前社交用户生成一个会员信息账号，以后这个社交账号就对应指定的会员信息）
            // 调用远程服务 gulimall-member 登陆或注册操作
            R r = oauthLogin(socialUserVo);
            if (r.getCode() == 0) {
                Member2 Member2 = r.getData("data", new TypeReference<Member2>() {
                });
                log.info("微博用户登录成功，用户信息：{}", Member2);
                session.setAttribute(AuthServerConstant.LOGIN_USER, Member2);

                return "redirect:http://localhost:3000";
            } else {
                return "redirect:http://localhost:3000/login";
            }

        } else { // 远程请求社交服务获取数据失败
            return "redirect:http://localhost:3000/login";
        }



    }

    @PostMapping("/oauth/login")
    public R oauthLogin(@RequestBody SocialUserVo socialUserVo) throws Exception {
        Member2 member2 = member2Service.login(socialUserVo);
        if (member2 != null) {
            return R.ok().data(member2);
        } else {
            return R.error(BizCodeEnume.LOGINACCT_PASSSWORD_INVAILD_EXCEPTION.getCode(), BizCodeEnume.LOGINACCT_PASSSWORD_INVAILD_EXCEPTION.getMsg());
        }
    }
}
